programming4us
           
 
 
SQL Server

SQL Server 2005 : Managing XML Data (part 2) - The xml Data Type and Methods

- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
10/24/2010 4:40:41 PM

The xml Data Type and Methods

The xml data type lets you store XML documents in a field within an SQL Server database or lets you store a variable within a procedure. By using the xml data type, you can store a complete document in a singular column. XML fragments are also supported. An XML fragment is similar to an XML document, but it is missing a single top-level element. There is a limit to the size of a fragment; its stored XML data cannot exceed 2GB.

XML data stored by itself is referred to as untyped XML. If you optionally associate an XML schema collection with the data, the XML becomes typed, meaning that the definition for the stored XML is also stored. The saved schemas in the collection are used to validate and define the XML.

The xml data type is treated in the same manner as any of the other data types. When used in a table, an XML column can have defaults assigned, can have constraints in place, and can be used as a source or result for computed columns. An XML column cannot be a primary or foreign key, and if the XML data is typed (that is, has an associated schema), the schema must be provided with the definition.

Let’s look at a practical example of using an xml data type. In the following example, resumes submitted for online job applications store educational background information into a table called Education. General name and address information is stored in a table called EmployeeProspect. EmployeeProspect has an XML column named Education:

UPDATE ONE.dbo.EmployeeProspect
SET Education =
(SELECT A.*
FROM ONE.dbo.Education A, ONE.dbo.EmployeeProspect B
WHERE A.ProspectID = B.ProspectID
FOR XML AUTO)

The easiest way to populate an XML column or variable is simply to send the results of a query by using the FOR XML clause. In this example, the results were sent to the Education table before the data was placed in an XML column, which made it easier to illustrate the use of FOR XML. However, other techniques can be used to eliminate the need for the Education table altogether, as you will see a little later in the chapter. Normally, you would receive XML from a web service or other source outside SQL Server, which would then be deposited into a field of the xml data type.

Note

You can download from the website for this book a file called PROSPECTS.XLS. You can use this file to set up the EmployeeProspect table used in the examples in this chapter. To import the file into a table and database, follow the instructions in the ProspectsReadMe.txt file.


XML AUTO by itself provides untyped XML. You can produce typed data by using XML AUTO, TYPE. The enhanced OPENROWSET functionality allows you to bulk-load XML documents into the xml data type columns in the database. 

XML Method Interactions

The xml data type has several directly associated methods. The following xml data type methods allow for querying, modifying, and reporting on the xml data type:

  • query()— Executes a query over XML and returns the untyped XML result of the query.

  • value()— Extracts a value of SQL type from an XML instance.

  • exist()— Determines whether a query returns a result.

  • modify()— Is used in the SET statement or SET clause of an UPDATE command to alter the content of an XML document.

  • nodes()— Helps shred XML into relational data.

Alert

xml data type methods are queried heavily on all SQL Server certification exams. Expect to see two to three questions in this area.


xml data type methods are considered subqueries and are therefore not permitted in areas where subqueries are not allowed. Because of this, the xml data type methods cannot be used in the PRINT statement or within the GROUP BY clause.

The query() Method

By using the query() method, you can return portions of XML. In its simplest form, you supply to the query() method the path through the XML that is desired. The information returned to you is the elements from the path and any subordinate elements and attributes. The information returned is XML data. To return the entire XML set, you use a query() method and supply only the appropriate root identifier, as shown in the following:

SELECT Education.query('/A') FROM EmployeeProspect

To return a subset of the information, you continue through the XML path, providing the necessary level to produce the desired results. The following example pulls from the XML the extra curricular elements only, identified by <EXTRA>, and any subordinates:

SELECT Education.query('/A/EXTRA') FROM EmployeeProspect
<EXTRA>Chess Club President</EXTRA><EXTRA>Valedictorian</EXTRA>
<EXTRA>Student Body President</EXTRA>
<EXTRA>Varsity Basketball</EXTRA>
<EXTRA />
<EXTRA />
NULL
<EXTRA>Volleyball</EXTRA><EXTRA>Basketball</EXTRA>
<EXTRA />
<EXTRA>Gymnastics</EXTRA><EXTRA>Cheerleaders</EXTRA>
<EXTRA />
<EXTRA />
<EXTRA />
<EXTRA>Debating Team</EXTRA><EXTRA>Ping Pong</EXTRA>
<EXTRA />
<EXTRA />
<EXTRA />
<EXTRA />
<EXTRA />
<EXTRA>Bowling</EXTRA><EXTRA>Golf</EXTRA>
<EXTRA>Basketball</EXTRA><EXTRA>Baseball</EXTRA>
NULL
<EXTRA />


The value() Method

The value() method is similar to the query() method except that it returns a SQL data type instead of an xml data type. You use this method to extract values from XML data. You can specify SELECT queries that combine or compare XML data with data in non-XML columns. You can also produce standard SQL-style reports based on the XML data.

You can retrieve individual attributes by using the @ sign prior to the attribute name within the supplied path. The following query illustrates how you can display a standard SQL column report that combines information from the SQL data type columns and from within the xml data type column:

SELECT ProspectID, FirstName + ' ' + LastName AS Name,
Education.value('(/A/@SCHOOL)[1]', 'varchar(40)') AS School
FROM EmployeeProspects
ProspectID Name School
---------- ------------------- ----------------------------------------
ACKE0001 Pilar Ackerman Maple Grove High
BARB0001 Angela Barbariol Illinois Tech School
BARR0001 Adam Barr Wabash University
BONI0001 Luis Bonifaz Northern CC
BUCH0001 Nancy Buchanan Univ of IL
CHEN0001 John Chen NULL
CLAY0001 Jane Clayton Elgin CC
DELA0001 Aidan Delaney DuPage
DIAZ0001 Brenda Diaz Roosevelt High School
DOYL0001 Jenny Doyle Heartland CC

The ordinal [1] indicates that the first subordinate is to be used. If multiple schools were present in the data, only the first in each record would be returned.

The exist() Method

You can perform an existence test against data by using the exist() method. For example, the following query resolves who in the data set has a degree:

SELECT ProspectID, Education.exist('/A/@DEGREE')
FROM EmployeeProspects
EmployeeID
---------- -----
ACKE0001 0
BARB0001 1
BARR0001 1
BONI0001 1
BUCH0001 1
CHEN0001 NULL
CLAY0001 1
DELA0001 1
DIAZ0001 0
DOYL0001 1

This method returns a 0, 1, or NULL, depending on whether data in the specified query is found, not found, or null. Our data sample would return 0 for anyone with XML present but no degree, 1 for anyone with a degree, and NULL for anyone with no associated data in the XML column.

The modify() Method

You use the modify() method to update an XML document. You can change the content of an XML type variable or column similarly to how you would change the content of any other SQL type column or variable. The modify() method takes an XML DML statement. XML DML provides statements to insert, update, or delete nodes from data. You use the modify() method in the SET clause of an UPDATE statement, as in the following example:

UPDATE Education
SET Education.modify('replace value of(/A/@DEGREE)[1] with "MA"')
WHERE ProspectID = 'DOYL0001'

Three different XML DML commands can be executed through the modify() method: insert, replace value of, and delete. The replace value of keywords are similar to the traditional SQL UPDATE statement. The insert keyword allows for the addition of one or more nodes or siblings, as in the following:

UPDATE Education
SET Education.modify('insert
<A SCHOOL="Univ of IL" DEGREE="MA"
MAJOR="Speech and Communica" GPA="3.3"
GRADYEAR="1991"><EXTRA /></A>
after (/A)[1]')
WHERE ProspectID = 'BUCH0001'

When after is used, the new node(s) is placed after the position of the defined query as a sibling. When before is used, the new node(s) is placed in front of the position as a sibling. When into is used, you specify as last or as first, and the new nodes are placed accordingly as descendants of the node identified by the query.

You can also specify the delete keyword with the modify() method to remove nodes from the XML:

UPDATE Education
SET Education.modify('delete /A/EXTRA')
WHERE ProspectID = 'BUCH0001'

The nodes() Method

You use the nodes() method to shred XML into relational data. It allows you to identify nodes that will be mapped into a new row of a recordset. The recordset contains copies of the original XML. You can retrieve multiple values from the recordset to provide a standard SQL report.

Unlike the other methods, nodes() is used as the source of a query in the FROM clause of the SELECT statement. You can either query directly from an XML variable or use CROSS APPLY on a table to an XML column contained within the table, as illustrated in the following example:

SELECT ProspectID, RTRIM(FirstName) + ' ' + Lastname AS Name,
T.Loc.value('@SCHOOL', 'varchar(40)') AS School,
T.Loc.value('@DEGREE', 'varchar(5)') AS Degree
FROM Education CROSS APPLY Education.nodes('/A') AS T(Loc)
ProspectID Name School Degree
---------- ----------------- -------------------------- ------
ACKE0001 Millar Ackerman Maple Grove High
BARB0001 Angela Barbariol Illinois Tech School AS
BARR0001 Adam Barr Wabash University BS
BONI0001 Luis Bonifaz Northern CC AA
BUCH0001 Nancy Buchanan Univ of IL BA
BUCH0001 Nancy Buchanan Univ of IL MA
CLAY0001 Jane Clayton Elgin CC AA
DELA0001 Aidan Delaney DuPage BA
DIAZ0001 Brenda Diaz Roosevelt High School
DOYL0001 Jenny Doyle Heartland CC AA
ERIC0001 Gregory Erickson Harvard University BS
Other -----------------
- SQL Server : Removing Unwanted Data
- SQL Server : Changing What Is Already Stored
- Using System Tables and Views
- SQL Server 2005 : Data Querying Using Full-Text Indexes
- SQL Dependency Reporting
- The Overall Disaster Recovery Process
- Microsoft SQL Server Options for Disaster Recovery
- How to Approach Disaster Recovery
- SQL Server 2008 : Database Mirroring
- Creating and Using a SQL Azure Database
- SQL Server 2008 : Failover Clustering
- SQL Server 2008 Reporting Services : Management and Security
- SQL Server 2008: Security and User Administration - Authentication Methods
- SQL Server 2008: Security and User Administration - Managing Principals (part 2) - Roles
- SQL Server 2008: Security and User Administration - Managing Principals (part 1) - Users
- SQL Server 2008: Security and User Administration - Managing Securables
- SQL Server 2008: Security and User Administration - Managing Permissions
- SQL Server 2008: Security and User Administration - Managing SQL Server Logins
- Managing SQL Server Permissions (part 4) - Using T-SQL to Manage Permissions
- Managing SQL Server Permissions (part 2) - Using SSMS to Manage Permissions at the Object Level
 
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
programming4us programming4us